package com.hwg.emp.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hwg.emp.model.UserMD;
import com.hwg.emp.service.ServiceFactroy;
import com.hwg.emp.service.UserService;

public class UpdatePasswordController extends HttpServlet{
       @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	   // TODO Auto-generated method stub
    	//// 2调用业务层对象业务方法
    	UserService service =  ServiceFactroy.getService(UserService.class);
    	//获取密码修改页面传入的 老密码和新密码
    	String oldpsw = req.getParameter("oldPsw");
    	String newpsw = req.getParameter("newPsw2");
        //获取当前用户
    	UserMD user = (UserMD)req.getSession().getAttribute("USER");
    	//新建用户 重新设置用户属性
    	UserMD newUser = new UserMD(); 
        //不用修改的属性设置成当前用户的属性  
    	newUser.setAccount(user.getAccount());
    	newUser.setId(user.getId());
    	newUser.setName(user.getName());
    	if (oldpsw.equals(user.getPassword())) {
			 try {
				//如果输入的密码和老密码一致 就设置新的密码
				newUser.setPassword(newpsw);
				//调用服务修改密码
				service.updatePassword(newUser);
				req.setAttribute("Msg", "密码修改成功");
		    	req.getRequestDispatcher("/welcome.jsp").forward(req, resp);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
	    	 req.setAttribute("Msg", "对不起修改密码失败");
	    	 req.getRequestDispatcher("/pages/updatePassword.jsp").forward(req, resp);
	     }
    }
}
